package com.cci.kangdao.controller.shankang.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cci.kangdao.cipFleet.entity.CipFleetT;
import com.cci.kangdao.controller.shankang.service.ShanKangSycMedbFleetService;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.service.impl.WwidFleetServiceImpl;
import com.cci.kangdao.utilTool.HttpUtils;
import com.cci.kangdao.utilTool.ThreadPoolUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 陕康云 同步  medb车队
 */
@Service
public class ShanKangSycMedbFleetImpl implements ShanKangSycMedbFleetService {
    private Logger log = Logger.getLogger(this.getClass().getName());
    @Value("${medbAddFleet}")
    private String MEDB_ADD_FLEET;

    @Value("${medbUpdateFleet}")
    private String MEDB_UPDATE_FLEET;

    @Value("${medbDeleteFleet}")
    private String MEDB_DELETE_FLEETURL;

    @Autowired
    private WwidFleetServiceImpl wwidFleetService;

    @Value("${medbWWID}")
    private String MEDB_WWID;

    /**
     * medb 添加车队
     * @param cipFleetT
     * @param userTSelect
     * @param esnList
     * @return
     */
    @Override
    public Long sycAddMedbFleet(CipFleetT cipFleetT, UserT userTSelect, List<String> esnList) {
        JSONObject jsonObject = this.getParam(cipFleetT, userTSelect, esnList);
        String token = wwidFleetService.getToken();
        Header tokenHeader = new BasicHeader("token", token);
        Header wwidHeader = new BasicHeader("wwid", MEDB_WWID);
        Header content = new BasicHeader("Content-Type", "application/json");
        Long shanKangFleetId = null;
        String resultStr = HttpUtils.postJson(MEDB_ADD_FLEET, jsonObject.toString(), new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response)
                    throws IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return EntityUtils.toString(httpEntity);
                } else {
                    log.info("获取 MEDB_ADD_FLEET 失败；打印地址：" + MEDB_DELETE_FLEETURL + "；token：" + token + "；wwid：" + JSON.toJSONString(userTSelect));
                    log.info("获取 MEDB_ADD_FLEET 失败；打印参数：" + jsonObject.toJSONString() + "；返回结果：" + response.toString());
                }
                return null;
            }
        }, tokenHeader, wwidHeader, content);
        log.info("获取 MEDB_ADD_FLEET 成功；打印地址：" + MEDB_DELETE_FLEETURL + "；token：" + token + "；wwid：" + JSON.toJSONString(userTSelect));
        log.info("获取 MEDB_ADD_FLEET 成功；打印参数：" + jsonObject.toJSONString() + "；返回结果：" + resultStr);
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject resultJson = JSONObject.parseObject(resultStr);
            if (resultJson.getInteger("code") == 0) {
                shanKangFleetId = resultJson.getJSONObject("data").getLong("fleetId");
            }
        }
        return shanKangFleetId;
    }
    /**
     * medb 参数拼接
     * @param cipFleetT
     * @param userTSelect
     * @param esnList
     * @return
     */
    public JSONObject getParam(CipFleetT cipFleetT, UserT userTSelect, List<String> esnList) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fleetName", cipFleetT.getFleetName()); //车队名称
        jsonObject.put("salePlant", Arrays.asList("XCEC"));//销售实体
        jsonObject.put("realFleet", "是");//真实车队： 是|否
        jsonObject.put("roadType", cipFleetT.getApplicationType() == 0 ? "道路" : "非道路");//道路非道路： 道路|非道路
        jsonObject.put("fuelType", cipFleetT.getFleetType() == 0 ? "GAS" : "FUEL");//燃油类型： FUEL|GAS
        jsonObject.put("province", "");//所属省
        jsonObject.put("city", "");//所属市
        jsonObject.put("headName", userTSelect.getUserName()); //车队负责人
        jsonObject.put("headPhone", userTSelect.getPhone());//负责人联系方式
        jsonObject.put("esnList", esnList);//车队esn 列表
        jsonObject.put("creatorWwid", userTSelect.getShankangWWID());//车队创建者（WWID
        jsonObject.put("creatorName", userTSelect.getUserName());  //车队创建者用户名
        jsonObject.put("source", "XCEC-SKY");//业务来源：目前仅支持三个：XCEC-SKY（西康陕康云）；DCEC-LYH （东康老友汇）；eCummins-APP（e路康明斯app）
        if (null != cipFleetT.getExternalFleetId()) {
            jsonObject.put("fleetId", cipFleetT.getExternalFleetId());
        }
        return jsonObject;
    }
    /**
     * medb 修改车队
     * @param cipFleetT
     * @param userTSelect
     * @param esnList
     * @return
     */
    @Override
    public Long sycUpdateMedbFleet(CipFleetT cipFleetT, UserT userTSelect , List<String> esnList) {
        JSONObject jsonObject = this.getParam(cipFleetT, userTSelect, esnList);
        String token = wwidFleetService.getToken();
        Header tokenHeader = new BasicHeader("token", token);
        Header wwidHeader = new BasicHeader("wwid", MEDB_WWID);
        Header content = new BasicHeader("Content-Type", "application/json");
        Long shanKangFleetId = null;
        String resultStr = HttpUtils.postJson(MEDB_UPDATE_FLEET, jsonObject.toString(), new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response)
                    throws IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return EntityUtils.toString(httpEntity);
                } else {
                    log.info("获取 MEDB_UPDATE_FLEET 失败；打印地址：" + MEDB_DELETE_FLEETURL + "；token：" + token + "；wwid：" +  JSON.toJSONString(userTSelect));
                    log.info("获取 MEDB_UPDATE_FLEET 失败；打印参数：" + jsonObject.toJSONString() + "；返回结果：" + response.toString());
                }
                return null;
            }
        }, tokenHeader, wwidHeader, content);
        log.info("获取 MEDB_UPDATE_FLEET 成功；打印地址：" + MEDB_DELETE_FLEETURL + "；token：" + token + "；wwid：" + JSON.toJSONString(userTSelect));
        log.info("获取 MEDB_UPDATE_FLEET 成功；打印参数：" + jsonObject.toJSONString() + "；返回结果：" + resultStr);
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject resultJson = JSONObject.parseObject(resultStr);
            if (resultJson.getInteger("code") == 0) {
                shanKangFleetId = resultJson.getJSONObject("data").getLong("fleetId");
            }
        }
        return shanKangFleetId;
    }

    /**
     * 删除车队
     * @param fleetId
     * @param wwid
     */
    @Override
    public void sycdeleteMedbFleet(Long fleetId, String wwid) {
        ThreadPoolUtil.newTask(new Thread(() -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("fleetId", fleetId);
            jsonObject.put("creatorWwid", wwid);
            String token = wwidFleetService.getToken();
            Header tokenHeader = new BasicHeader("token", token);
            Header wwidHeader = new BasicHeader("wwid", MEDB_WWID);
            Header content = new BasicHeader("Content-Type", "application/json");
            String resultStr = HttpUtils.postJson(MEDB_DELETE_FLEETURL, jsonObject.toString(), new ResponseHandler<String>() {
                @Override
                public String handleResponse(HttpResponse response)
                        throws IOException {
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity httpEntity = response.getEntity();
                        return EntityUtils.toString(httpEntity);
                    } else {
                        log.info("获取 MEDB_FLEET_LIST 失败；打印地址：" + MEDB_DELETE_FLEETURL + "；token：" + token + "；wwid：" + wwid);
                        log.info("获取 MEDB_FLEET_LIST 失败；打印参数：" + jsonObject.toJSONString() + "；返回结果：" + response.toString());
                    }
                    return null;
                }
            }, tokenHeader, wwidHeader, content);
            log.info("获取 MEDB_FLEET_LIST 成功；打印地址：" + MEDB_DELETE_FLEETURL + "；token：" + token + "；wwid：" + wwid);
            log.info("获取 MEDB_FLEET_LIST 成功；打印参数：" + jsonObject.toJSONString() + "；返回结果：" + resultStr);
        }));
    }
}
